package com.daxue.configtest.others;

import lombok.AllArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author daxue0929
 * @date 2023/3/23
 */

@AllArgsConstructor(staticName = "of")
public class PageWalker<T> {
    public static final Integer INIT_INDEX = 0;
    public static final Integer PAGE_SIZE = 200;
    public static final Pageable INIT_PAGEABLE = PageRequest.of(INIT_INDEX, PAGE_SIZE, Sort.unsorted());

    private boolean hasNext;
    private Pageable pageable;
    private Function<Pageable, Slice<T>> pageSupplier;

    public static <R> PageWalker<R> of(Pageable pageable, Function<Pageable, Slice<R>> pageSupplier) {
        return new PageWalker<>(true, pageable, pageSupplier);
    }

    public Boolean hasNext() {
        return hasNext;
    }

    public Slice<T> next() {
        Slice<T> slice = pageSupplier.apply(pageable);
        hasNext = slice.hasNext();
        pageable = pageable.next();
        return slice;
    }

    public void walk(Consumer<Slice<T>> consumer) {
        while (hasNext) {
            consumer.accept(next());
        }
    }
}
